package org.jsola.hr.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.jsola.config.entity.SiteConfigDO;
import org.jsola.hr.common.HrLogKit;
import org.jsola.hr.constant.ConfigCodeConstants;
import org.jsola.hr.entity.CompanyDO;
import org.jsola.hr.entity.EmpInfoDO;
import org.jsola.hr.provider.IMessageProviderService;
import org.jsola.hr.provider.ISiteConfigProviderService;
import org.jsola.hr.service.ICompanyService;
import org.jsola.hr.service.IEmpSendSmsService;
import org.jsola.message.dto.ShortMessageDTO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author zhr
 */
@Service("hrEmpSendSmsServiceImpl")
public class EmpSendSmsServiceImpl implements IEmpSendSmsService {

    @Autowired
    private IMessageProviderService messageProviderService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private ISiteConfigProviderService siteConfigProviderService;


    @Override
    public int sendEntrySms(List<EmpInfoDO> empInfoList, TokenUser tokenUser) {
        int successCount = 0;
        for (EmpInfoDO empInfoDO : empInfoList) {
            if (StringUtils.isEmpty(empInfoDO.getPhone())) {
                continue;
            }
            CompanyDO companyDO = companyService.selectDOById(empInfoDO.getCompanyId(), tokenUser.getSiteId());
            if (Objects.isNull(companyDO)) {
                continue;
            }
            String thirdId = siteConfigProviderService.selectValueByCode(ConfigCodeConstants.CODE_ENTRY_SMS_THIRD_ID,
                    tokenUser.getSiteId());
            //发送短信验证码
            ShortMessageDTO shortMessageDTO = new ShortMessageDTO();
            shortMessageDTO.setPhone(empInfoDO.getPhone());
            shortMessageDTO.setThirdId(thirdId);

            Map<String, Object> params = new HashMap<>();
            params.put("userName", empInfoDO.getName());
            params.put("companyName", companyDO.getName());
            shortMessageDTO.setParams(params);
            shortMessageDTO.setScene("入职短信");
            boolean sendSuccess = messageProviderService.sendShortMessage(shortMessageDTO, tokenUser);

            HrLogKit.logForSave("给员工发送入职短信,empId:" + empInfoDO.getId() + ",phone:" + empInfoDO.getPhone(), "sendEntrySms", empInfoDO.getId(), tokenUser);

            if (sendSuccess) {
                successCount++;
            }
        }
        return successCount;
    }
}




